package com.cafe.pro.util;

import com.cafe.pro.dto.KeyPairConfig;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class CryptoUtils {
    // RSA加密AES密钥
    public static String encryptWithRsa(String data, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("RSA加密失败", e);
        }
    }

    // RSA解密AES密钥
    public static String decryptWithRsa(String data, PrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("RSA解密失败", e);
        }
    }

    // AES加密数据（ECB模式，确保相同明文生成相同密文）
    public static String encryptWithAes(String data, String aesKey) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("AES加密失败", e);
        }
    }

    // AES解密数据
    public static String decryptWithAes(String encryptedData, String aesKey) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decrypted);
        } catch (Exception e) {
            throw new RuntimeException("AES解密失败", e);
        }
    }

    public static void main(String[] args) throws Exception {
        String aesKey = "my-secret-key-13";
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfcJoVae6jkdzqyBQuWDo1Hab7lwtDkIE9UPhkw6wE/l2i6HO2O8PCp2+ZWsC6J6KnReXAHXRjgmUNy8VU6UNpYSpYjjlEZaZWes6RsMd3Uyq/zpuPIBJYB9fsnaN8J5rQOWvf9eD9OoS3GM3cabIgTLdpxvmcGw1WQSYnBR94NCYHqvgqfljPKlUcN4yn5da7pO3IQJthCHpirJd7xVB2P052zfokrSnP0Q2vvR8q9QgiZImhTGGuKfZfsPRfqp2yi5Hq7rIiJz8nm318nT/5D5/OvlUPX2HAmiJC5OttjjdgLDJV3fHMKmx0g3xr/OBZd2zyOtdTCEgQt5A+uc8/AgMBAAECggEAG1ISNSUnzUOLVXffbWmU39Eq8eWZ+oPigX1Ecw/MhDaKGQY3/bwT+WDzkJWqfLuZ9YvWqKrjbMHFSy3lrH0kHgSWWwJT8dJxRFRa3UArjdjkdGWU5luaiRce+t6wSvAGaTPNtlzNptbGMxG/BMvfyAUdULTVxNgl2ufi/8Cy+cfAhvo0QyfEYJZFhVC3Fd1bp8SeuD1F6pt3P/ArPz7xKBbDbSanC8yMe6WsbaVzPsN+Tw0fX5iAp8Yp+1KncEpu44hYYtekp46PE3TayX8rm1U5Ah2pWKoQZ1TVQSOn+YQgHDOnZ6I5hyRWzdF5F7E0GuKgZIc6ji8yeSuaa34VAQKBgQDBgr6k9e/qwJwKqm80l+YBDzwmu4zON36p5/RC4lgt20jZT86I+XC2+0q/iNjDRG/vawl9BA8h6i09MqcuwAwMX5SlNa3NTA/nL3+Tg453WSiPz/t9ehFXn0LBfUj5DEs3ktw+8r1zOknbfFbX+KZMvN2Zd/SLZgD2Zip/+saBQQKBgQDS7URV0ZM6TTryJFDt0c0xVWnE+nc0tG0YNZ2WIOwCTXU3Ax1v7XfNmYZZYhLMDWSn9FNJ9wNXYEIqcEWpp2sojddsHG2KQ01myUmXfRf32LyzF+mnP4OKWWQ4vhx9xienBs81Gg0XXRWjBTUaDUAmXvGP1o/P4gvoqLnA0aOwfwKBgQCt3c91YBQElLKfUqtAUgqygQHGu1S0JGCGQIbTYZNhAFngBzjHEXgYsIhkt4wrRl5ce4u26+K80i97gPt9ocgxhd+E4Uob32+ahK7X16g1y8IKFREdmIPkeo/8UZkzS7x5XlbNqERYN9MMhhdxTVP+NuPUdFcguLG8secVvjiFAQKBgBOxkYrNuYhdA57uIxxBVX5AslJw7EZgfjsfbmpBAqgoYURUpx/3NRNePTwFOyoQKhDAcDJcvNQgqazatLZlakzsCWwPr26UYBqzuopJZL6AXwX9upQiCv8U35WosnJP2Q3wRdJ4bzZ6O3XwG4gmKpIqlTVP3DeVrHT5o/ZL3JOzAoGANB9vooJXiMHGU2jERFSRD1rXXAT2b8UK8Nn5OSUt5Z50weguCuMWbzlt/PlTI0kebh4OWpXA4LEIF+/JX4AqhOCkQvxFQEprj02BVDB5+NFZhNf6ou4cUf7jYPkXA1biK6lt4T6esBsrFDzQfMex/JfJXj3hDla/bnwVQBZ1L98=";
        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3CaFWnuo5Hc6sgULlg6NR2m+5cLQ5CBPVD4ZMOsBP5douhztjvDwqdvmVrAuieip0XlwB10Y4JlDcvFVOlDaWEqWI45RGWmVnrOkbDHd1Mqv86bjyASWAfX7J2jfCea0Dlr3/Xg/TqEtxjN3GmyIEy3acb5nBsNVkEmJwUfeDQmB6r4Kn5YzypVHDeMp+XWu6TtyECbYQh6YqyXe8VQdj9Ods36JK0pz9ENr70fKvUIImSJoUxhrin2X7D0X6qdsouR6u6yIic/J5t9fJ0/+Q+fzr5VD19hwJoiQuTrbY43YCwyVd3xzCpsdIN8a/zgWXds8jrXUwhIELeQPrnPPwIDAQAB";
        KeyPairConfig keyPairConfig = new KeyPairConfig(publicKey, privateKey);
        PublicKey aPublic = KeyUtil.parseKeyPair(keyPairConfig).getPublic();
        String encryptedAesKey = CryptoUtils.encryptWithRsa(aesKey, aPublic);
        System.out.println(encryptedAesKey);
    }
}
